package com.hkts.naturalgas.dictionaries.controller;

import com.hkts.naturalgas.dictionaries.entity.HktsEnvironmentProtectionDictionaries;
import com.hkts.naturalgas.dictionaries.entity.HktsEnvironmentProtectionItem;
import com.hkts.naturalgas.dictionaries.service.IHktsEnvironmentProtectionDictionariesService;
import com.hkts.naturalgas.dictionaries.service.IHktsEnvironmentProtectionItemService;
import com.hkts.naturalgas.dictionaries.utils.DBUtils;
import com.hkts.naturalgas.dictionaries.utils.ExcleCache;
import com.hkts.naturalgas.dictionaries.vo.ExcleCacheCacheVo;
import com.hkts.naturalgas.utils.ExcelPortUtil;
import com.hkts.naturalgas.utils.Result;
import com.hkts.naturalgas.utils.ResultUtil;
import com.hkts.naturalgas.utils.TestDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @ClassNameExportController
 * @Description
 * @Author yck
 * @Date2021-06-23 16:09
 * @Version V1.0
 **/
@RestController
@RequestMapping("/instrumentdata/exportData")
@Slf4j
public class ExportDataController {
    @Autowired
    public IHktsEnvironmentProtectionDictionariesService iHktsEnvironmentProtectionDictionariesService;
    @Autowired
    public IHktsEnvironmentProtectionItemService iHktsEnvironmentProtectionItemService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    public DBUtils dBUtils;

    @ResponseBody
    @GetMapping("/exportFile1")
    /** 功能描述:
     *[date 日期, section 早班晚班 1 早班 2 晚班, workshop 车间 1是 煅烧， 2 是焙烧, response]
     * @return: com.hkts.naturalgas.utils.Result
     * @Author: 杨春科
     * @Date: 2021-06-24 10:21
     * @Description //TODO
     */
    public Result exportData(String date, String section, String workshop, HttpServletResponse response) throws Exception {
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = new HktsEnvironmentProtectionDictionaries();
        hktsEnvironmentProtectionDictionaries.setIsExport("1");
        hktsEnvironmentProtectionDictionaries.setIsEnable("1");
        hktsEnvironmentProtectionDictionaries.setWorkShop(workshop);
        List<HktsEnvironmentProtectionDictionaries> hktsEnvironmentProtectionDictionaries1 = iHktsEnvironmentProtectionDictionariesService.selectList(hktsEnvironmentProtectionDictionaries);
        XSSFWorkbook wb = new XSSFWorkbook();
        for (int i = 0; i < hktsEnvironmentProtectionDictionaries1.size(); i++) {
            HktsEnvironmentProtectionItem item = new HktsEnvironmentProtectionItem();
            item.setTableId(hktsEnvironmentProtectionDictionaries1.get(i).getId());
            item.setIsEnable("1");
            item.setIsExport("1");
            List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = iHktsEnvironmentProtectionItemService.selectList(item);

            List<Map<String, Object>> list = dBUtils.getList(hktsEnvironmentProtectionDictionaries1.get(i), hktsEnvironmentProtectionItems, date, section);

            XSSFSheet sheet = wb.getSheet(hktsEnvironmentProtectionDictionaries1.get(i).getTableDescribe());
            wb = ExcelPortUtil.getSheet(wb, hktsEnvironmentProtectionItems, list, hktsEnvironmentProtectionDictionaries1.get(i).getTableDescribe());
        }
        if (workshop.equals("1")) {
            workshop = "煅烧车间";
        } else {
            workshop = "焙烧车间";
        }
        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        // 设置文件头
        response.setHeader("Content-Disposition",
                "attchement;filename=" + new String((workshop + ".xls").getBytes("gb2312"), "ISO8859-1"));
        response.setContentType("application/msexcel");
        wb.write(output);
        wb.close();
        return null;
    }

    @ResponseBody
    @GetMapping("/exportFile")
    /** 功能描述:
     *
     * @return: com.hkts.naturalgas.utils.Result
     * @Author: 杨春科
     * @Date: 2021-06-24 10:21
     * @Description //TODO
     */
    public Result exportFile(String beginDate, String endDate, String tableId, String timeStamp, Integer granularity, HttpServletResponse response) throws Exception {

        log.info("---------数据同步开始----------");
        Long startTime = System.currentTimeMillis();

        CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
            HktsEnvironmentProtectionDictionaries byId = iHktsEnvironmentProtectionDictionariesService.getById(tableId);
            ExcleCache.excleCache.put(timeStamp, ExcleCacheCacheVo.getExcleCacheCacheVo(timeStamp, byId.getTableDescribe()));
            try{
                XSSFWorkbook wb = new XSSFWorkbook();
                String[] strings = {beginDate, endDate};
                List<String> daysByTime = TestDataUtils.getDaysByTime(strings);
                System.out.println(daysByTime.toString());
                HktsEnvironmentProtectionItem item = new HktsEnvironmentProtectionItem();
                item.setTableId(tableId);
                item.setIsEnable("1");
                item.setIsExport("1");
                List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = iHktsEnvironmentProtectionItemService.selectList(item);

                List<Map<String, Object>> list = dBUtils.getTenSecondsExport(byId, hktsEnvironmentProtectionItems, TestDataUtils.getStart(beginDate), TestDataUtils.getEnd(endDate), granularity);
                log.info("数据长度：{}", list.size());


                for (int i = 0; i < daysByTime.size(); i++) {
                    String time = daysByTime.get(i);
                    List<Map<String, Object>> time1 = list.stream().filter(map -> map.get("time").toString().startsWith(time)).collect(Collectors.toList());
                    log.info(daysByTime.get(i) + ":{}", time1.size());
                    wb = ExcelPortUtil.getSheet(wb, hktsEnvironmentProtectionItems, time1, time);
                }
                Long endTime = System.currentTimeMillis();
                Long tempTime = (endTime - startTime);
                log.info("定时任务花费时间：" +
                        (((tempTime / 86400000) > 0) ? ((tempTime / 86400000) + "d") : "") +
                        ((((tempTime / 86400000) > 0) || ((tempTime % 86400000 / 3600000) > 0)) ? ((tempTime % 86400000 / 3600000) + "h") : ("")) +
                        ((((tempTime / 3600000) > 0) || ((tempTime % 3600000 / 60000) > 0)) ? ((tempTime % 3600000 / 60000) + "m") : ("")) +
                        ((((tempTime / 60000) > 0) || ((tempTime % 60000 / 1000) > 0)) ? ((tempTime % 60000 / 1000) + "s") : ("")) +
                        ((tempTime % 1000) + "ms"));
                // 输出Excel文件
                String property = System.getProperty("user.dir");
                System.out.println(property);
                String path = property + "\\enviroment-data-interface\\src\\main\\resources\\excle\\" + timeStamp + ".xlsx";

                System.out.println(path);
                File file = new File(path);
                file.createNewFile();
                FileOutputStream fos = new FileOutputStream(file.getPath());
                wb.write(fos);
                fos.close();
                ExcleCache.excleCache.get(timeStamp).setState("1");
                log.info("制表完成！！！：{}",timeStamp);
            }catch (Exception e){
                e.printStackTrace();
            }
        }, threadPoolExecutor);

        return ResultUtil.success("正在制表");
    }

    @ResponseBody
    @GetMapping("/downExcle")
    public void downLoad(String timeStamp, HttpServletResponse response) throws Exception {
        String property = System.getProperty("user.dir");
        ExcleCacheCacheVo excleCacheCacheVo = ExcleCache.excleCache.get(timeStamp);
        String path = property + "\\enviroment-data-interface\\src\\main\\resources\\excle\\" + timeStamp + ".xlsx";
        File file = new File(path);
        String filename = excleCacheCacheVo.getFileName() + ".xlsx";
        response.setContentType("application/msexcel");
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gb2312"), "iso8859-1"));
        byte[] buffer = new byte[1024];
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;

        OutputStream os = null; //输出流
        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer);
                i = bis.read(buffer);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            bis.close();
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //删除缓存和文件
        ExcleCache.excleCache.remove(timeStamp);
        file.delete();
    }

    @ResponseBody
    @GetMapping("/getState")
    public Result getState(String timeStamp) {
        ExcleCacheCacheVo excleCacheCacheVo = ExcleCache.excleCache.get(timeStamp);
        return ResultUtil.data(excleCacheCacheVo.getState());
    }


    @ResponseBody
    @GetMapping("/exportFileByTableId")
    /** 功能描述:
     *[date 日期, section 早班晚班 1 早班 2 晚班, workshop 车间 1是 煅烧， 2 是焙烧, response]
     * @return: com.hkts.naturalgas.utils.Result
     * @Author: 杨春科
     * @Date: 2021-06-24 10:21
     * @Description //TODO
     */
    public Result exportDataByTableId(String startTime, String endTime, String tableId, HttpServletResponse response) throws Exception {
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = new HktsEnvironmentProtectionDictionaries();
        hktsEnvironmentProtectionDictionaries.setIsExport("1");
        hktsEnvironmentProtectionDictionaries.setIsEnable("1");
        hktsEnvironmentProtectionDictionaries.setId(tableId);
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries1 = iHktsEnvironmentProtectionDictionariesService.getTableId(tableId, "1", "1");
        XSSFWorkbook wb = new XSSFWorkbook();

        HktsEnvironmentProtectionItem item = new HktsEnvironmentProtectionItem();
        item.setTableId(hktsEnvironmentProtectionDictionaries1.getId());
        item.setIsEnable("1");
        item.setIsExport("1");
        List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = iHktsEnvironmentProtectionItemService.selectList(item);
        String[] strings = {startTime, endTime};
        List<String> daysByTime = TestDataUtils.getDaysByTime(strings);
        for (int i = 0; i < daysByTime.size(); i++) {
            List<Map<String, Object>> list = dBUtils.getListExport(hktsEnvironmentProtectionDictionaries1, hktsEnvironmentProtectionItems, TestDataUtils.getStart(daysByTime.get(i)), TestDataUtils.getEnd(daysByTime.get(i)));
            wb = ExcelPortUtil.getSheet(wb, hktsEnvironmentProtectionItems, list, daysByTime.get(i));
        }
        //XSSFSheet sheet = wb.getSheet(hktsEnvironmentProtectionDictionaries1.getTableDescribe());
        // 输出Excel文件

        OutputStream output = response.getOutputStream();
        response.reset();
        // 设置文件头
        response.setHeader("Content-Disposition",
                "attchement;filename=" + new String((hktsEnvironmentProtectionDictionaries1.getTableDescribe() + ".xls").getBytes("gb2312"), "ISO8859-1"));
        response.setContentType("application/msexcel");
        wb.write(output);
        wb.close();
        return null;
    }
}
